from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema
from rest_framework.request import Request
from rest_framework.viewsets import ModelViewSet
from rest_framework.filters import SearchFilter

from demoapp.models import DemoTable
from demoapp.serializers import DemoSerializer


@extend_schema(tags=['users'])
class DemoViewSet(ModelViewSet):
    queryset = DemoTable.objects.all()
    serializer_class = DemoSerializer

    # permission_classes = [] # 移除全局权限
    # pagination_class = None # None不分页; PageNumberPagination 自定分页

    # 列表 get post     -->        list/create
    # 详情 get put patch delete --> retrieve/update/partial-update/destroy

    # 精确匹配
    # filter_backends = [DjangoFilterBackend]  # 默认全局
    filterset_fields = ['name', 'description']  # 查询字段名和查询参数名 ?name=xxxx 字段名也得name, =

    # 模糊匹配
    # filter_backends = [SearchFilter]  # 默认全局
    search_fields = ['name', 'description']

    @extend_schema('create', request=DemoSerializer)
    def create(self, request:Request, *args, **kwargs):
        return super().create(request, *args, **kwargs)
